// 下载文档流
/**
 * 下载文档流文件
 * @param res 文档流数据
 * @param type 文件类型后缀名
 * @param filename 下载后的文件名
 */
export const download = (res: any, type: string, filename: string) => {
     // 使用映射表替代大量的if/else if语句，提高代码可读性和维护性
     const mimeTypeMap: Record<string, string> = {
          word: 'application/msword',
          zip: 'application/zip',
          pdf: 'application/pdf;chartset=UTF-8',
          xls: 'application/vnd.ms-excel',
          xlsx: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
          dxf: 'application/dxf',
          jpg: 'image/jpeg',
          jpeg: 'image/jpeg',
          png: 'image/png',
          gif: 'image/gif',
          svg: 'image/svg+xml',
          txt: 'text/plain',
          docx: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
          ppt: 'application/vnd.ms-powerpoint',
          pptx: 'application/vnd.openxmlformats-officedocument.presentationml.presentation',
     }

     // 获取文件的MIME类型，如果没有找到则使用默认值
     const mimeType = mimeTypeMap[type.toLowerCase()] || ''

     // 创建blob对象，解析流数据
     const blob = new Blob([res], {
          type: mimeType,
     })

     // 创建下载链接并触发下载
     const a = document.createElement('a')
     const URL = window.URL || window.webkitURL
     const href = URL.createObjectURL(blob)

     a.href = href
     a.download = filename

     // 触发下载并清理
     document.body.appendChild(a)
     a.click()
     document.body.removeChild(a)
     window.URL.revokeObjectURL(href)
}
/**
 * 将Base64编码的字符串转换为文件并下载
 * @param base64String Base64编码的字符串，格式应为"data:[MIME类型];base64,[编码内容]"
 * @param fileName 下载后的文件名
 */
export const downloadToBase64 = (base64String: string, fileName: string) => {
     // 将base64字符串转换为Blob对象
     const arr = base64String.split(',')
     const mimeMatch = arr[0].match(/:(.*?);/)

     // 安全检查，确保base64字符串格式正确
     if (!mimeMatch || mimeMatch.length < 2) {
          console.error('Invalid base64 string format')
          return
     }

     const mime = mimeMatch[1]
     const bstr = atob(arr[1])
     const n = bstr.length
     const u8arr = new Uint8Array(n)

     // 将二进制字符串转换为Uint8Array
     for (let i = 0; i < n; i++) {
          u8arr[i] = bstr.charCodeAt(i)
     }

     const blob = new Blob([u8arr], { type: mime })

     // 创建下载链接并触发下载
     const URL = window.URL || window.webkitURL
     const url = URL.createObjectURL(blob)
     const a = document.createElement('a')

     a.href = url
     a.download = fileName

     // 触发下载并清理
     document.body.appendChild(a)
     a.click()
     window.URL.revokeObjectURL(url)
     a.remove()
}
